package com.astrocsr.dao;

import java.util.List;

import org.hibernate.Query;
import org.springframework.stereotype.Repository;

import com.astrocsr.domain.bean.TblUser;

@Repository("userDAO")
public class UserDAO extends BaseHelperDAO {

	public static final String USER_ID 		= "userId";
	public static final String EMAIL 		= "email";

	public TblUser findById(Object id) throws Exception {
		List<TblUser> list = findByProperty(USER_ID, id);
		if (list != null && list.size() > 0)
			return list.get(0);
		return null;
	}
	
	public List<TblUser> findByEmail(Object email) throws Exception {
		return findByProperty(EMAIL, email);
	}

	@SuppressWarnings("unchecked")
	public List<TblUser> findByProperty(String propertyName, Object value) throws Exception {

		try {

			String queryString = "from TblUser as model where model."
					+ propertyName + "= :propertyName";
			Query query = getCurrentSession().createQuery(queryString);
			query.setParameter("propertyName", value);
			return query.list();
		} catch (RuntimeException re) {
			throw re;
		}
	}
	
	@SuppressWarnings("unchecked")
	public List<TblUser> listTblUser() throws Exception {
		List<TblUser> result = null;
		
		String queryString = "from TblUser"; // Hibernate Query Language
		result = getCurrentSession().createQuery(queryString).list();
		
		return result;
	}
	
	/**
	 * Insert customer into database
	 */
	public void addTblUser(TblUser entity) throws Exception {
		// Insert into database
		getCurrentSession().save(entity);
	}
	

	/**
	 * Change password
	 */
	public void updatePassword(TblUser tblUser) throws Exception {

		Query query = getCurrentSession().getNamedQuery("TblUser.UpdatePassword");
		query.setParameter("password", 		tblUser.getPassword());
		query.setParameter("updatedBy", 	tblUser.getUpdatedBy());
		query.setParameter("updatedDate", 	tblUser.getUpdatedDate());
		query.setParameter("email", 		tblUser.getEmail());
		query.executeUpdate();
	}

}